package com.huan.cola.customer.gatewayimpl;

import com.huan.cola.customer.convertor.CustomerConvertor;
import com.huan.cola.customer.domain.gateway.CustomerGateway;
import com.huan.cola.customer.domain.model.Customer;
import com.huan.cola.customer.dto.event.CustomerCreateEvent;
import com.huan.cola.customer.event.DomainEventPublisher;
import com.huan.cola.customer.gatewayimpl.database.CustomerMapper;
import com.huan.cola.customer.gatewayimpl.database.dataobject.CustomerDO;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huan.fu
 * @date 2022/6/7 - 11:24
 */
@Repository
public class CustomerGatewayImpl implements CustomerGateway {

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private DomainEventPublisher domainEventPublisher;

    @Override
    public List<Customer> findAll() {
        return customerMapper.findAll()
                .stream()
                .map(CustomerConvertor::toDomainObject)
                .collect(Collectors.toList());
    }

    @Override
    public boolean existsPhone(String phone) {
        return customerMapper.existsPhone(phone) > 0;
    }

    @Override
    public int create(Customer customer) {
        CustomerDO customerDO = CustomerConvertor.toDataObject(customer);
        customerDO.setId(null);
        int result = customerMapper.insert(customerDO);

        // 发布领域事件
        if (result > 0) {
            CustomerCreateEvent customerCreateEvent = new CustomerCreateEvent(customerDO.getId());
            domainEventPublisher.publisher(customerCreateEvent);
        }
        return result;
    }
}
